package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constrant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author FCJ
 * @date 2020-01-11 14:24
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private ReportService reportService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private MemberService memberService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();//获取日历对象，模拟时间就是当前时间
        //计算过去一年十二个月
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获得时间往后推一个月
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months", months);

        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        if (memberCount == null) {
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);

        }
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            Map<String, Object> setmealCount = setmealService.findSetmealCount();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, setmealCount);

        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }

    @RequestMapping("/getBusinessReport")
    public Result getBusinessReport() {
        try {
            Map<String, Object> report = reportService.getBusinessReport();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, report);

        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> businessReport = reportService.getBusinessReport();
            String reportDate = (String) businessReport.get("reportDate");
            Integer todayNewMember = (Integer) businessReport.get("todayNewMember");
            Integer totalMember = (Integer) businessReport.get("totalMember");
            Integer thisWeekNewMember = (Integer) businessReport.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) businessReport.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) businessReport.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) businessReport.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) businessReport.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) businessReport.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) businessReport.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) businessReport.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeals = (List<Map<String, Object>>) businessReport.get("hotSetmeal");
//获取Excel模板文件绝对路径
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //获取模板文件 创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            sheet.getRow(2).getCell(5).setCellValue(reportDate);

            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(5).setCellValue(todayNewMember);
            row4.getCell(7).setCellValue(totalMember);

            XSSFRow row5 = sheet.getRow(5);
            row5.getCell(5).setCellValue(thisWeekNewMember);
            row5.getCell(7).setCellValue(thisMonthNewMember);

            XSSFRow row7 = sheet.getRow(7);
            row7.getCell(5).setCellValue(todayOrderNumber);
            row7.getCell(7).setCellValue(todayVisitsNumber);

            XSSFRow row8 = sheet.getRow(8);
            row8.getCell(5).setCellValue(thisWeekOrderNumber);
            row8.getCell(7).setCellValue(thisWeekVisitsNumber);

            XSSFRow row9 = sheet.getRow(9);
            row9.getCell(5).setCellValue(thisMonthOrderNumber);
            row9.getCell(7).setCellValue(thisMonthVisitsNumber);

            for (int i = 0; i < hotSetmeals.size(); i++) {
                XSSFRow row = sheet.getRow(i + 12);
                row.getCell(4).setCellValue((String) hotSetmeals.get(i).get("name"));
                row.getCell(5).setCellValue((String) hotSetmeals.get(i).get("setmeal_count"));
                row.getCell(6).setCellValue((String) hotSetmeals.get(i).get("proportion"));
            }

            //通过输出流进行文件下载
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
        }

    }
}
